I converted a project to Typescript (not perfectly but 0 errors at least) and found out some interesting things!
Async return type
For normal functions you could do something like
function func(): string {}
but if it’s async you need to surround the type with
Promise<>
async function func(): Promise<string> {}
Inline type annotation for object
I had an object as a parameter and had to do something like this:
export function editMode({ selectedList, listItemsUl, API_BASE, headerName }: {selectedList: List, listItemsUl: HTMLUListElement, API_BASE: string, headerName: HTMLDivElement })
If you’re feeling less silly you could do this:
interface EditModeParams {
selectedList: List;
listItemsUl: HTMLUListElement;
API_BASE: string;
headerName: HTMLDivElement; }
export function editMode(params: EditModeParams) {}
I also had to do this but using
as
, for exampleitemListArray.push({ title: listItemInput.value, checked: false } as {title: string, checked: boolean});
Type cast event targets
I found that I had to cast the targets as actual elements to use things like
.value
properly.let currentTarget = e.target as HTMLInputElement;
Inlay hints
Kind of wish I had this enabled before converting everything but there is a feature in VSCode which inlays the inferred types inline so you can see if they match with the actual types you want!
To enable them search for
typescript inlay
in Settings and enable the ones you want. I enabled everything 😇You can also configure the color with
"editorInlayHint.background": "red",
"editorInlayHint.foreground": "black"
cssText
Apparently .style doesn’t work in Typescript so you have to type .style.cssText instead!